<template>
  <!-- 日期选择弹框 -->
  <view class="modal-mask" v-if="visible" @tap="closeModal">
    <view class="date-picker" @tap.stop>
      <!-- 重新设计的顶部导航栏 -->
      <view class="new-header">
        <!-- 月份选择器 - 修改为原生picker -->
        <view class="selector-group">
          <view class="arrow-icon" @tap="prevMonth">❮</view>
          <picker 
            mode="selector" 
            :range="monthNames" 
            :value="currentMonth"
            @change="handleMonthSelect"
            class="month-picker"
          >
            <view class="selector-box">
              <text class="selector-text">{{ monthDisplay }}</text>
              <tm-icon name="tmicon-angle-down" :font-size="20" color="#333"></tm-icon>
            </view>
          </picker>
          <view class="arrow-icon" @tap="nextMonth">❯</view>
        </view>
        
        <!-- 年份选择器 -->
        <view class="selector-group">
          <view class="arrow-icon" @tap="prevYear">❮</view>
          <picker 
            mode="selector" 
            :range="yearOptions" 
            :value="yearDefaultIndex"
            @change="handleYearSelect"
            class="year-picker"
          >
            <view class="selector-box">
              <text class="selector-text">{{ currentYear }}</text>
              <tm-icon name="tmicon-angle-down" :font-size="20" color="#333"></tm-icon>
            </view>
          </picker>
          <view class="arrow-icon" @tap="nextYear">❯</view>
        </view>
      </view>

      <!-- 星期标题 -->
      <view class="week-header">
        <text v-for="day in weekDays" :key="day" class="week-day">{{ day }}</text>
      </view>

      <!-- 日期网格 -->
      <view class="calendar-grid">
        <view 
          v-for="(date, index) in visibleDates" 
          :key="index"
          :class="[
            'date-cell',
            date.month !== currentMonth ? 'other-month' : '',
            isSelected(date) ? 'selected' : '',
            isToday(date) ? 'today' : ''
          ]"
          @tap="selectDate(date)"
        >
          <text class="date-text">{{ date.date }}</text>
        </view>
      </view>

      <!-- 底部按钮 - 调整了样式 -->
      <view class="footer-buttons">
        <text class="btn clear" @tap="clearSelection">清空</text>
        <view style="flex-grow: 1;"></view>
        <text class="btn cancel" @tap="cancel">取消</text>
        <text class="btn ok" @tap="confirm">确定</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import tmIcon from '@/tmui/components/tm-icon/tm-icon.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['confirm', 'cancel'])

// 数据
const currentDate = ref(new Date())
const selectedDate = ref<Date | null>(null)
const yearDefaultIndex = ref(10) // 默认选中当前年份在列表中的位置

// 常量
const weekDays = ['一', '二', '三', '四', '五', '六', '日']
const monthNames = [
  '一月', '二月', '三月', '四月', '五月', '六月',
  '七月', '八月', '九月', '十月', '十一', '十二'
]

// 计算属性
const currentYear = computed(() => currentDate.value.getFullYear())
const currentMonth = computed(() => currentDate.value.getMonth())
const monthDisplay = computed(() => monthNames[currentMonth.value])

const yearOptions = computed(() => {
  const years = []
  const startYear = currentYear.value - 100
  for (let i = 0; i < 200; i++) {
    years.push(startYear + i)
  }
  return years
})

const visibleDates = computed(() => {
  const year = currentYear.value
  const month = currentMonth.value
  
  // 计算当前月第一天是周几（周日为0）
  const firstDay = new Date(year, month, 1).getDay()
  // 当前月最后一天
  const lastDate = new Date(year, month + 1, 0).getDate()
  
  // 生成当前月所有日期
  const dates = []
  for (let i = 1; i <= lastDate; i++) {
    dates.push({
      date: i,
      month: month,
      year: year,
      fullDate: new Date(year, month, i)
    })
  }
  
  // 补充上月末尾日期（根据新的星期顺序调整）
  const prevMonthLastDate = new Date(year, month, 0).getDate()
  // 由于星期顺序改为从周一开始，需要调整补充的天数
  const daysToPrepend = (firstDay + 6) % 7
  for (let i = daysToPrepend; i > 0; i--) {
    dates.unshift({
      date: prevMonthLastDate - i + 1,
      month: month - 1,
      year: month === 0 ? year - 1 : year,
      fullDate: new Date(month === 0 ? year - 1 : year, month - 1, prevMonthLastDate - i + 1)
    })
  }
  
  // 补充下月开头日期（确保网格满6行）
  const totalCells = 42 // 6行×7列
  const nextMonthStart = dates.length
  for (let i = 1; i <= totalCells - dates.length; i++) {
    dates.push({
      date: i,
      month: month + 1,
      year: month === 11 ? year + 1 : year,
      fullDate: new Date(month === 11 ? year + 1 : year, month + 1, i)
    })
  }
  
  return dates
})

// 月份选择处理
const handleMonthSelect = (e: any) => {
  const index = e.detail.value
  if (index >= 0 && index <= 11) {
    const newDate = new Date(currentDate.value)
    newDate.setMonth(index)
    currentDate.value = newDate
  }
}

// 年份选择处理
const handleYearSelect = (e: any) => {
  const index = e.detail.value
  if (index >= 0 && index < yearOptions.value.length) {
    const selectedYear = yearOptions.value[index]
    const newDate = new Date(currentDate.value)
    newDate.setFullYear(selectedYear)
    currentDate.value = newDate
  }
}

const selectDate = (date: any) => {
  if (date.month !== currentMonth.value) {
    currentDate.value = date.fullDate
  }
  selectedDate.value = date.fullDate
}

const isSelected = (date: any) => {
  if (!selectedDate.value) return false
  return (
    date.date === selectedDate.value.getDate() &&
    date.month === selectedDate.value.getMonth() &&
    date.year === selectedDate.value.getFullYear()
  )
}

const isToday = (date: any) => {
  const today = new Date()
  return (
    date.date === today.getDate() &&
    date.month === today.getMonth() &&
    date.year === today.getFullYear()
  )
}

const clearSelection = () => {
  selectedDate.value = null
}

const cancel = () => {
  emit('cancel')
  clearSelection()
}

const confirm = () => {
  if (selectedDate.value) {
    emit('confirm', selectedDate.value)
  }
  clearSelection()
}

const closeModal = () => {
  cancel()
}

// 新增加的月份/年份切换方法
const prevMonth = () => {
  const newDate = new Date(currentDate.value)
  const newMonth = newDate.getMonth() - 1
  newDate.setMonth(newMonth)
  
  // 如果月份减1后小于0，则自动年份减1
  if (newMonth < 0) {
    newDate.setFullYear(newDate.getFullYear() - 1)
    newDate.setMonth(11) // 设置为12月
  }
  
  currentDate.value = newDate
}

const nextMonth = () => {
  const newDate = new Date(currentDate.value)
  const newMonth = newDate.getMonth() + 1
  newDate.setMonth(newMonth)
  
  // 如果月份加1后大于11，则自动年份加1
  if (newMonth > 11) {
    newDate.setFullYear(newDate.getFullYear() + 1)
    newDate.setMonth(0) // 设置为1月
  }
  
  currentDate.value = newDate
}

const prevYear = () => {
  const newDate = new Date(currentDate.value)
  newDate.setFullYear(newDate.getFullYear() - 1)
  currentDate.value = newDate
}

const nextYear = () => {
  const newDate = new Date(currentDate.value)
  newDate.setFullYear(newDate.getFullYear() + 1)
  currentDate.value = newDate
}

// 初始化时设置默认值
onMounted(() => {
  yearDefaultIndex.value = yearOptions.value.indexOf(currentYear.value)
  if (yearDefaultIndex.value === -1) yearDefaultIndex.value = 10
})
</script>

<style scoped>
/* 弹窗背景 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

/* 日期选择器容器 */
.date-picker {
  width: 90%;
  max-width: 400px;
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

/* 新设计的顶部导航栏 */
.new-header {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 24px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 12px;
}

.month-picker,
.year-picker {
  display: flex;
  align-items: center;
  justify-content: center;
}

.selector-group {
  display: flex;
  align-items: center;
  border-radius: 6px;
  overflow: hidden;
  padding: 2px;
}

.selector-box {
  display: flex;
  align-items: center;
  padding: 4px 12px;
  min-width: 80px;
  justify-content: center;
  cursor: pointer;
}

.selector-text {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-right: 4px;
}

.arrow-icon {
  padding: 6px 10px;
  font-size: 18px;
  color: #666;
  cursor: pointer;
  transition: background-color 0.2s;
}

.arrow-icon:active {
  background-color: #e6e6e6;
}

/* 星期标题 */
.week-header {
  display: flex;
  justify-content: space-around;
  padding: 12px 0;
}

.week-day {
  width: 14.28%;
  text-align: center;
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

/* 日历网格 */
.calendar-grid {
  display: flex;
  flex-wrap: wrap;
  min-height: 252px; /* 6行×42px */
}

.date-cell {
  width: 14.28%;
  height: 42px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.date-text {
  width: 32px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  font-size: 14px;
  color: #333;
}

.other-month .date-text {
  color: #ccc;
}

.selected .date-text {
  background-color: #ff9500;
  color: white;
}

.today .date-text {
  color: #ff9500;
  font-weight: bold;
}

/* 底部按钮 - 修改了样式 */
.footer-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
  margin-top: 12px;
}

.btn {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  background-color: transparent !important;
  border: none;
}

/* 使用选中日期的橙色 */
.clear {
  color: #ff9500;
}

.cancel {
  color: #ff9500;
}

.ok {
  color: #ff9500; /* 使用与选中日期相同的颜色 */
}

.cancel:hover, .ok:hover, .clear:hover {
  background-color: rgba(0, 0, 0, 0.05) !important;
}
</style>